package cn.kgc.spring.factory;

import cn.kgc.spring.annotations.Autowired;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author 课工场
 * @date 2024/4/26
 * @description 实例工厂  创建对象
 */
public class BeanFactory {

    private static final Map<String, Object> beans = new HashMap<>();

    static {
        // 解析配置文件
        ResourceBundle resourceBundle = ResourceBundle.getBundle("beans");
        // 创建对象
        resourceBundle.keySet()
                .forEach(k -> {
                    String className = resourceBundle.getString(k);
                    try {
                        Class<?> aClass = Class.forName(className);
                        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
                        Object o = declaredConstructor.newInstance();
                        beans.put(k,o);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
        // 初始化对象  遍历beans
        beans.forEach((k,v)->{

            Class<?> aClass = v.getClass();

            Field[] declaredFields = aClass.getDeclaredFields();
            if (declaredFields!=null){
                for (Field declaredField : declaredFields) {
                    Autowired annotation = declaredField.getAnnotation(Autowired.class);
                    if (annotation!=null){
                        String name = declaredField.getName();
                        // 根据属性名从beans容器中获取对应的 object    UserService userService      o->  UserServiceImpl
                        Object o = beans.get(name);
                        try {
                            // 提升私有属性的操作权限
                            declaredField.setAccessible(true);
                            declaredField.set(v,o);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

    }


    public static <T> T getBean(Class<T> type) {
        try {
            Constructor<T> declaredConstructor = type.getDeclaredConstructor();
            T t = declaredConstructor.newInstance();
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    // 根据beanName 获取实例对象
     public static Object getBean(String beanName){
        return beans.get(beanName);
     }

    public static <T> T getBean(String beanName,Class<T> type){
        Object o = beans.get(beanName);
        T cast = type.cast(o);
        return cast;
    }
}



